﻿
/*
 * 反SQL注入
 * 实现方法：
 * 1、检测url中是否有sql注入特征
 * 2、检测input输入框中是否有sql注入特征
 */

/*
 * 如果页面中原本有window.onload事件，则先进行调用，以免影响原有的代码功能，下同
 */
var pre_window_load=window.onload;
if (pre_window_load!=undefined){
    pre_window_load();
}

/*
 * 页面加载完成后执行
 */
window.onload=function(){
    console.log("anti_sql_inject module loaded");

    //判断url中是否有sql注入语句
    var url = location.search.toLowerCase();
    url = url.substring(url.indexOf("?"));
    
    if( regexp_detect_sqlinj(url) == true ){
        alert("SQL inject detected!");
        document.body.innerHTML=""
    }

    //判断input输入框中没有没sql注入语句
    var input = document.getElementsByTagName("input");
    for(var i=0; i<input.length; i++){

        //获取之前的onblur事件
        var pre_blur = input[i].onblur;

        //注册blur事件处理程序，即onblur
        input[i].addEventListener("blur",function(){

            //如果之前有oncblur事件处理程序，则先执行
            if(pre_blur!=undefined){
                pre_blur;
            }
            detect_input_sqlinj(this);
        });

    }
    
}

function detect_input_sqlinj(t){

    if(regexp_detect_sqlinj(t.value) == true){
        alert("SQL inject detected!");
        t.value="";
    }
}

/* 检测SQL注入 */
function regexp_detect_sqlinj(str_to_detect){

    for(i=0; i< regexp_rule.length; i++){
        if(regexp_rule[i].test(str_to_detect) == true){
            console.log("Detected SQL inject attack,regexp rule:", "(" + i + ")", regexp_rule[i]);

            //判断BrowserWAF_BrowserID是否定义
            if(typeof BrowserWAF_BrowserID != "undefined"){
                //向后台提交浏览器指纹
                ajax_insert_browserid();
            }

            return true;
        }
    }
    return false;
}

//正则表达式检测规则
regexp_rule = [
    /select.+(from|limit)/i,
    /(?:(union(.*?)select))/i,
    /sleep\((\s*)(\d*)(\s*)\)/i,
    /group\s+by.+\(/i,
    /(?:from\W+information_schema\W)/i,
    /(?:(?:current_)user|database|schema|connection_id)\s*\(/i,
    /\s*or\s+.*=.*/i,
    /order\s+by\s+.*--$/i,
    /benchmark\((.*)\,(.*)\)/i,
    /base64_decode\(/i,
    /(?:(?:current_)user|database|version|schema|connection_id)\s*\(/i,
    /(?:etc\/\W*passwd)/i,
    /into(\s+)+(?:dump|out)file\s*/i,
    /xwork.MethodAccessor/i,
    /(?:define|eval|file_get_contents|include|require|require_once|shell_exec|phpinfo|system|passthru|preg_\w+|execute|echo|print|print_r|var_dump|(fp)open|alert|showmodaldialog)\(/i,
    /\<(iframe|script|body|img|layer|div|meta|style|base|object|input)/i,
    /(onmouseover|onmousemove|onerror|onload)\=/i,
    /javascript:/i,
    /\.\.\/\.\.\//i,
    /\|\|.*(?:ls|pwd|whoami|ll|ifconfog|ipconfig|&&|chmod|cd|mkdir|rmdir|cp|mv)/i,
    /(?:ls|pwd|whoami|ll|ifconfog|ipconfig|&&|chmod|cd|mkdir|rmdir|cp|mv).*\|\|/i,
    /(gopher|doc|php|glob|file|phar|zlib|ftp|ldap|dict|ogg|data)\:\//i
];

